package com.lemon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lemon.domain.PageResult;
import com.lemon.domain.Pcd;
import com.lemon.domain.User;
import com.lemon.domain.Warehouse;
import com.lemon.domain.pageParam.WarehousePageParam;
import com.lemon.domain.vo.WarehouseVo;
import com.lemon.mapper.PcdMapper;
import com.lemon.mapper.WarehouseMapper;
import com.lemon.service.WarehouseService;
import com.lemon.utils.UserThreadLocal;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {
    private final WarehouseMapper warehouseMapper;

    private final PcdMapper pcdMapper;

    @Override
    public PageResult getPage(WarehousePageParam param) {
        PageHelper.startPage(param.getPage(),param.getPageSize());
        List<Warehouse> list = warehouseMapper.getPage(param);
        Page page = (Page) list;
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void updateWarehouse(Warehouse warehouse) {
        extracted(warehouse);
        warehouse.setUpdateTime(LocalDateTime.now());
        warehouseMapper.updateById(warehouse);
    }

    @Override
    public List<WarehouseVo> getWarehouseList() {
        List<WarehouseVo> vo = warehouseMapper.getWarehouseList();
        return vo;
    }

    @Override
    public void add(Warehouse warehouse) {
        extracted(warehouse);
        User user = UserThreadLocal.get();
        warehouse.setCreateTime(LocalDateTime.now());
        warehouse.setPersonChargeId(user.getId());
        warehouse.setPersonChargeName(user.getName());
        warehouseMapper.insert(warehouse);
    }

    /**
     * 根据城市id获取省份数据
     * @param warehouse
     */
    private void extracted(Warehouse warehouse) {
        Pcd pcd = pcdMapper.selectById(warehouse.getCityId());
        warehouse.setCityName(pcd.getName());
        warehouse.setProvinceId(pcd.getParentId());
        Pcd pcd1 = pcdMapper.selectById(warehouse.getProvinceId());
        warehouse.setProvinceName(pcd1.getName());
    }

}
